﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevExpress.Data.Filtering;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.ExpressApp.Editors;
using DevExpress.ExpressApp.Layout;
using DevExpress.ExpressApp.Model.NodeGenerators;
using DevExpress.ExpressApp.SystemModule;
using DevExpress.ExpressApp.Templates;
using DevExpress.ExpressApp.Utils;
using DevExpress.Persistent.Base;
using DevExpress.Persistent.Validation;
using AturableWira.Module.BusinessObjects.ACC.GL;

namespace AturableWira.Module.Controllers
{
    // For more typical usage scenarios, be sure to check out https://documentation.devexpress.com/eXpressAppFramework/clsDevExpressExpressAppViewControllertopic.aspx.
    public partial class JVViewController : ViewController
    {
        public JVViewController()
        {
            InitializeComponent();
            // Target required Views (via the TargetXXX properties) and create their Actions.
        }
        protected override void OnActivated()
        {
            base.OnActivated();
            // Perform various tasks depending on the target View.
        }
        protected override void OnViewControlsCreated()
        {
            base.OnViewControlsCreated();
            // Access and customize the target View control.
        }
        protected override void OnDeactivated()
        {
            // Unsubscribe from previously subscribed events and release other references and resources.
            base.OnDeactivated();
        }

        private void JVPostAction_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            foreach (JournalVoucher jv in View.SelectedObjects)
            {
                foreach(JournalEntry je in jv.Entries)
                {
                    GLBudget generalLedger = ObjectSpace.FindObject<GLBudget>(CriteriaOperator.Parse("Account=? And PeriodYear=?", je.Account, jv.PeriodYear));
                    if (generalLedger == null)
                    {
                        generalLedger = ObjectSpace.CreateObject<GLBudget>();
                        generalLedger.PeriodYear = jv.PeriodYear;
                        generalLedger.Account = ObjectSpace.GetObjectByKey<GLAccount>(je.Account.AccountNumber);
                    }

                    GLTotal gLTotal = ObjectSpace.FindObject<GLTotal>(CriteriaOperator.Parse("Account=? And PeriodYear=?", je.Account, jv.PeriodYear));
                    if (gLTotal == null)
                    {
                        gLTotal = ObjectSpace.CreateObject<GLTotal>();
                        gLTotal.PeriodYear = jv.PeriodYear;
                        gLTotal.Account = ObjectSpace.GetObjectByKey<GLAccount>(je.Account.AccountNumber);
                    }
                }
                jv.Posted = true;
            }

            ObjectSpace.CommitChanges();
        }
    }
}
